﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Arch.Model
{
    public class Value
    {
        public override bool Equals(object obj)
        {
            return (obj != null) && HasSameBusinessSignatureAs(obj);
        }

        public override int GetHashCode()
        {
            if (_hashcodeCache.HasValue) return _hashcodeCache.Value;

            else unchecked
                {
                    _hashcodeCache = (GetType().GetHashCode() * HashcodeMultiplier);
                    //TODO : optimze this :
                    foreach (var property in GetType().GetProperties().Where(p => p.CanRead))
                    {
                        _hashcodeCache = _hashcodeCache ^ property.GetGetMethod().Invoke(this, new object[0]).GetHashCode();
                    }
                }

            return _hashcodeCache.Value;
        }

        private bool HasSameBusinessSignatureAs(object compareTo)
        {
            return GetHashCode().Equals(compareTo.GetHashCode());
        }

        private const int HashcodeMultiplier = 33;
        private int? _hashcodeCache;
    }
}
